package com.qf.filter;

import com.qf.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 鉴权过滤器，鉴定用户是否有权限访问
 *
 * @version v1.0.0
 * @Description:
 * @author: 姜红凯
 * @date: 2022.03.25
 * @since 1.0
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    /**
     * 过滤器中的鉴权业务
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //3.获取用户访问的uri路径
        String uri = request.getURI().getPath();

        //4.判断用户访问的路径是否为登录路径，认证路径，注册路径，如果是无条件放行
        if (uri.contains("/login")) {
            //放行
            return chain.filter(exchange);
        }

        //5.获取cookie中是否有jwt令牌
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        if (cookies == null) {
            //设置异常代码401，权限不足
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应
            return response.setComplete();
        }
        //获取第一个cookie名字叫做token的令牌内容
        HttpCookie httpCookie = cookies.getFirst("token");
        if (httpCookie == null) {
            //设置异常代码401，权限不足
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应
            return response.setComplete();
        }

        //6.如果cookie中没有令牌抛出401权限不足异常
        String jwt = httpCookie.getValue();
        if (StringUtils.isEmpty(jwt)) {
            //设置异常代码401，权限不足
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应
            return response.setComplete();
        }

        //7.解析jwt令牌
        try {
            JwtUtil.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            //8.如果解析异常说明令牌超时或者篡改抛出401权限不足异常
            //设置异常代码401，权限不足
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应
            return response.setComplete();
        }

        //9.放行
        return chain.filter(exchange);

    }

    //如果当前网关有多个过滤器，这里指定过滤器的执行顺序
    @Override
    public int getOrder() {
        return 0;
    }
}
